import { action, computed, observable } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Component } from 'react';
import './SuperTypeList.scss';

import { AutoList, Button, HeaderBar, ListItem, Modal, Page, TabItem } from '@/cross/components';

import { View } from '@/cross/components';

import DropDown from '@/cross/components/Picker/Dropdown';

import PutSuperType from './PutSuperType';

import { Client } from '@/config';
import { CrossPageProps } from '@/cross/pages/PropType';
import tagStore from '@/cross/stores/tag';
import { $api, $confirm, $message, $service, px } from '@/cross/utils';
import EditorStore from '@/pages/editor/store/page';
import { ApiTypeGetReqDto, ITypeEntity } from '../types';

interface IProps extends CrossPageProps {
  store?: EditorStore;
  params: {
    selector?: boolean;
    filter?: ApiTypeGetReqDto;
    showBack?: boolean;
    onSelect?: (item: ITypeEntity) => void;
  };
}

@inject('store')
@observer
class PageView extends Component<IProps> {
  componentDidMount() {
    this.refresh();
  }

  putModalRef: Modal<PutSuperType> | null = null;
  autoListRef: AutoList<ITypeEntity> | null = null;
  @observable tab = 0;
  @action changeTab = (val: number) => {
    this.tab = val;
    this.refresh();
  };
  @computed get tagsTree() {
    return tagStore.allTagData[4] || [];
  }

  refresh = () => {
    this.autoListRef?.refresh();
  };

  put = (item?: ITypeEntity) => {
    this.putModalRef?.open({
      // store: this.props.store,
      params: {
        item,
        onSave: () => {
          this.refresh();
        },
      },
    });
  };

  onItemAction = (action: 'edit' | 'remove' | 'more' | 'select', item: ITypeEntity) => {
    if (action === 'select') {
      this.props.params.onSelect?.(item);
      return this.props.navigation.goBack();
    }
    if (action === 'edit') {
      this.put(item);
    }
    if (action === 'remove') {
      $confirm('确认删除类型吗?')
        .then(() => {
          $service('rest', 'delete', {
            tableName: 'article',
            id: item._id,
          })
            .then(() => {
              $message.success('已删除');
              this.refresh();
            })
            .catch((e) => {
              if (e.errmsg) $message.error(e.errmsg);
            });
        })
        .catch(() => {});
    }
  };

  handleClickDropdown = (item: ITypeEntity, index: number) => {
    this.onItemAction(index === 0 ? 'remove' : 'more', item);
  };

  fetchData = (currentPage: number, pageSize?: number) => {
    return new Promise<ITypeEntity[]>((resolve) => {
      const params: ApiTypeGetReqDto = {
        currentPage,
        pageSize,
        // tag_id: this.tab ? this.tab : undefined,
      };
      const { filter } = this.props.params;
      if (filter) {
        Object.assign(params, filter);
      }
      $api
        .post('/type/get', params)
        .then((res) => {
          resolve(res.data);
        })
        .catch(() => {});
    });
  };

  renderItem = ({ item, index }: { item: ITypeEntity; index: number }) => {
    return (
      <View key={index} className="M-p-h-b-15">
        <ListItem
          title={item.desc || item.name}
          span={{
            left: [12, 12, 12],
            center: [2, 2, 2],
            right: [10, 10, 10],
          }}
          // avatar={require('../../assets/images/default_avatar.png')}
          center={
            <View className="M-vertical-middle M-p-l-5">
              <View>
                {/* <Text className='M-f-s-12 M-f-c-666'>
                  阅读
                </Text> */}
              </View>
            </View>
          }
          right={
            <View className="M-horizontal-right">
              <View className="M-vertical-middle">
                {this.props.params.selector && (
                  <Button
                    className="M-m-r-10"
                    onClick={this.onItemAction.bind(this, 'select', item)}
                  >
                    选择
                  </Button>
                )}
                <Button color="gray" onClick={this.onItemAction.bind(this, 'edit', item)}>
                  编辑
                </Button>
                <DropDown options={['删除']} onClick={this.handleClickDropdown.bind(this, item)}>
                  <Button color="gray" className="M-m-l-10">
                    更多
                  </Button>
                </DropDown>
              </View>
            </View>
          }
        />
      </View>
    );
  };

  render() {
    const { showBack = false } = this.props.params;
    return (
      <Page className="M-b-c-e type-list" {...this.props}>
        <HeaderBar
          title="超级类型"
          titleAlign="left"
          mode="dark"
          leftContent={null}
          showBack={showBack}
          bottomContent={
            <View className="M-flexbox-horizontal M-p-t-5 M-p-l-10">
              <TabItem
                title="全部"
                active={this.tab === 0}
                onClick={this.changeTab.bind(this, 0)}
              />
              {this.tagsTree.map((tag) => {
                return (
                  <TabItem
                    key={tag.tag_id}
                    title={tag.tag_name || ''}
                    active={this.tab === tag.tag_id}
                    onClick={this.changeTab.bind(this, tag.tag_id || 0)}
                  />
                );
              })}
            </View>
          }
          rightContent={
            <View className="M-p-r-10">
              <Button color="primary" onClick={this.put.bind(this, undefined)}>
                新建类型
              </Button>
            </View>
          }
          backgroundColor="#353535"
        />
        <View className="M-flexbox-vertical M-flex-item" style={{ backgroundColor: '#3e3e3e' }}>
          <AutoList<ITypeEntity>
            onFetchData={this.fetchData}
            renderHeader={<View className="M-p-t-5" />}
            renderItem={this.renderItem}
            gutter={[10, 10]}
            itemViewProps={{ col: true, md: 24, lg: 24, xl: 24, xxl: 24 }}
            ref={(node) => {
              this.autoListRef = node;
            }}
            emptyText="暂无类型"
          />
        </View>
        {/* Modal */}
        <Modal<PutSuperType>
          ref={(node) => (this.putModalRef = node)}
          zIndex={101}
          width={Client === 'worktop' ? px(2000) : px(750)}
          height={Client === 'worktop' ? 'calc(70vh)' : undefined}
          renderView={(props) => <PutSuperType {...props} />}
        />
      </Page>
    );
  }
}

export default PageView;
